package com.zwh.sharding.config.sharding.strategy;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.NumberFormat;
import java.util.Collection;

/**
 * @author zwh
 * @date 2023-5-16
 */
public class IntegerPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Integer> {
    private static final Logger logger = LoggerFactory.getLogger(DatePreciseShardingAlgorithm.class);
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Integer> shardingValue) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumIntegerDigits(2);
        String suffix = nf.format(shardingValue.getValue() % availableTargetNames.size());
        for (String targetName : availableTargetNames) {
            if (targetName.endsWith(suffix)) {
                logger.info("match suffix:" + suffix + ", targetName:{}" + targetName);
                return targetName;
            }
        }
        throw new IllegalArgumentException("未找到匹配的目标名称");
    }
}
